using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

    #region instance fields
    //instance fields
    protected System.Web.UI.WebControls.Image imgImage;
    private int THUMBNAIL_SIZE = 60;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// Creates an image, by querying the SQL database with the given img_pk
    /// parameter. The query will return a byte[] array, which represents the image.
    /// This byte[] array is then converted into an image and added to the placeholder
    /// control "plImage" which is on this page
    /// </summary>
    /// <param name="img_pk">The primary key to fetch the image data for</param>
    private void createImageFromDBBytes(int img_pk)
    {

        ThumbFromID.THUMBNAIL_SIZE = this.THUMBNAIL_SIZE;
        ThumbFromID.USE_SIZE_FOR_HEIGHT = false;
        imgImage = new System.Web.UI.WebControls.Image();
        // set the source to the page that generates the thumbnail image
        imgImage.ImageUrl = ThumbFromID.PAGE_NAME + "?" +
            ThumbFromID.IMAGE_ID + "=" + img_pk;
        litException.Visible = false;
        plImage.Controls.Clear();
        plImage.Controls.Add(imgImage);
    }

	/// <summary>
	/// returns a byte[] array which represents the input Image
	/// </summary>
	/// <param name="bmp">The source image to return as byte[] array</param>
	/// <returns>byte[] array which represents the input Image</returns>
    private byte[] BmpToBytes(System.Drawing.Image bmp)
    {
        MemoryStream ms = null;
        byte[] bmpBytes = null;
        try
        {
            ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            // read to end
            bmpBytes = ms.GetBuffer();
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            bmp.Dispose();
            if (ms != null)
            {
                ms.Close();
            }
        }
        return bmpBytes;
    }

    /// <summary>
    /// Will attempt ot save the posted file contents to SQL server
    /// table. Will firstly check that the posted file is an image
    /// </summary>
    /// <param name="sender">the btnSubmit</param>
    /// <param name="e">the btnSubmit EventArgs</param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string imgContentType = UploadFile.PostedFile.ContentType;

            //check if an image
            if (imgContentType.ToLower().StartsWith("image"))
            {
                //get the image from upload stream
                System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(UploadFile.PostedFile.InputStream);
                //get pk, to allow image to be created on this page from the
                //SQL server stores byte[] array
                int img_pk = 0;
                //store the image in database, and also ccheck to see if it was successful, and if so create 
                //a thumnail here of the stored image
                int RowsAffected = dbAccess.SaveImageToDB(ref img_pk,BmpToBytes(b));
                if (RowsAffected > 0)
                {
                    createImageFromDBBytes(img_pk);
                }
                else
                {
                    litException.Text = ("<br><p>ERROR saving image </p>");
                }
            }
            else
            {
                litException.Text = ("<br><p>The file is not an image</p>");
            }
        }
        catch (Exception ex)
        {
            litException.Text = ("<br><p>" + ex.Message + "</p>");
        }
    }


    /// <summary>
    /// Will attempt fetch all SQL server stored images, and will bind the resultant
    /// DataSet to the "dlImages" datalist on this page. When the databinding occurs
    /// the dlImages_ItemDataBound(..) event is fired. At that stage the image control
    /// is found, and a new thumbnail is constructed for each DataSet row value
    /// </summary>
    /// <param name="sender">the btnSeeAll</param>
    /// <param name="e">the btnSeeAll EventArgs</param>
    protected void btnSeeAll_Click(object sender, EventArgs e)
    {
        try
        {
            // set the source of the data for the repeater control and bind it
            DataSet dsImgs = dbAccess.GetImages();
            dlImages.DataSource = dsImgs;
            dlImages.DataBind();
        }
        catch (Exception ex)
        {
            litException.Text = ("<br><p>" + ex.Message + "</p>");
        }
    }


    /// <summary>
    /// Occurs when the server side DataList starts databinding. This event
    /// is used to intercept the databinding to create a new Image that
    /// uses the binary array value of the data within the DataList datasource
    /// </summary>
    /// <param name="sender">the datalist</param>
    /// <param name="e">the datalist DataListItemEventArgs</param>
    protected void dlImages_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        System.Web.UI.WebControls.Image img = null;

        // make sure this is an item in the data list (not header etc.)
        if ((e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            // get a reference to the image used for the bar in the row
            img = (System.Web.UI.WebControls.Image)
                (e.Item.FindControl("imgThumbnail"));

            //get the img_pk from DataRow being bound
            int img_pk = Convert.ToInt16(
                ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString());

            ThumbFromID.THUMBNAIL_SIZE = this.THUMBNAIL_SIZE;
            ThumbFromID.USE_SIZE_FOR_HEIGHT = false;
            // set the source to the page that generates the thumbnail image
            img.ImageUrl = ThumbFromID.PAGE_NAME + "?" +
                ThumbFromID.IMAGE_ID + "=" + img_pk;            
        }
    }
}
